package com.warmheart.core.rs.oper;

import java.util.Iterator;
import java.util.function.Function;

import javax.validation.constraints.NotNull;

import com.warmheart.core.cors.builder.CoRsBuilder;
import com.warmheart.core.cors.enums.DateFormatEnum;
import com.warmheart.core.rs.builder.RsBuilder;
import com.warmheart.core.rs.enums.FieldTypeEnum;
import com.warmheart.core.rs.model.SelectedModel;

/**
 * 
 * @ClassName: MultipleOper
 * @Description: 多字段查询字段配置类
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 * @param <T>
 * @param <E>
 */
public class MultipleOper<T extends CoRsBuilder<?, ?>, E extends RsBuilder<T>> {

    private final E e;

    private final T t;

    MultipleOper(E e) {
        this.e = e;
        this.t = this.e.core();
    }

    /**
     * 
     * @Title: next
     * @Description: 多字段查询后续字段添加
     * @author ZhangJianyang
     * @param function
     * @return
     */
    public <F> MultipleOper<T, E> next(@NotNull Function<E, Rs<T, E>> function) {
        Rs<T, E> rs = function.apply(this.e);
        Iterator<SelectedModel> iterator = this.t.getSelectedModelList().iterator();
        while (iterator.hasNext()) {
            SelectedModel element = iterator.next();
            if (rs.fetchField().equals(element.getFieldName())) {
                iterator.remove();
                // 由于每次添加都会进行字段检查，所有这里最多只可能有一个，可以直接中断循环
                break;
            }
        }
        this.t.getSelectedModelList().add(
                new SelectedModel(FieldTypeEnum.MULTIPLE_NEXT, rs.fetchField(), rs.fetchProp()));
        return this;
    }

    /**
     * 
     * @Title: chain
     * @Description: 通用多字段查询链路添加
     * @author ZhangJianyang
     * @param function
     * @return
     */
    public MultipleOper<T, E> chain(@NotNull Rs<? extends CoRsBuilder<?, ?>, ? extends RsBuilder<?>> rs,
            DateFormatEnum... dateFormatEnums) {
        Iterator<SelectedModel> iterator = this.t.getSelectedModelList().iterator();
        while (iterator.hasNext()) {
            SelectedModel element = iterator.next();
            if (rs.fetchField().equals(element.getFieldName())) {
                iterator.remove();
                // 由于每次添加都会进行字段检查，所有这里最多只可能有一个，可以直接中断循环
                break;
            }
        }
        this.t.getSelectedModelList().add(
                new SelectedModel(FieldTypeEnum.MULTIPLE_NEXT, rs.fetchField(), rs.fetchProp()));
        return this;
    }

    /**
     * 
     * @Title: end
     * @Description: 字段添加结束
     * @author ZhangJianyang
     * @return
     */
    public T end() {
        return this.t;
    }
}
